<template>
  <div class="room-management-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>会议室管理</h3>
          <el-button type="primary" @click="handleAdd">新增会议室</el-button>
        </div>
      </template>

      <!-- 会议室列表 -->
      <el-table :data="roomList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="会议室名称" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            {{ row.type === 'classroom' ? '教室型' : '圆桌型' }}
          </template>
        </el-table-column>
        <el-table-column prop="maxCapacity" label="座位数" />
        <el-table-column prop="roomEquipments" label="设备支持">
            <template #default="{ row }">
                <template v-if="row.roomEquipments && row.roomEquipments.length">
                    <el-tag 
                      v-for="equipment in row.roomEquipments" 
                      :key="equipment.equipmentId"  
                      style="margin-right: 5px; margin-bottom: 5px"
                    >
                      {{ equipment.equipmentName }}
                    </el-tag>
                </template>
                <span v-else>-</span>
            </template>
        </el-table-column>
        <el-table-column prop="hourlyRentalPrice" label="每小时价格">
          <template #default="{ row }">
            ¥{{ row.hourlyRentalPrice }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑会议室' : '新增会议室'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="会议室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入会议室名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="classroom">教室型</el-radio>
            <el-radio label="round_table">圆桌型</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="座位数" prop="maxCapacity">
          <el-input-number v-model="form.maxCapacity" :min="1" />
        </el-form-item>
        <el-form-item label="设备支持">
          <el-checkbox-group v-model="form.equipmentIds">
            <el-checkbox label="投影" value="1"/>
            <el-checkbox label="音响" value="2"/>
            <el-checkbox label="网络" value="3"/>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="每小时价格" prop="hourlyRentalPrice">
          <el-input-number 
            v-model="form.hourlyRentalPrice" 
            :min="0" 
            :precision="2" 
            :step="10"
          />
          <span class="ml-2">元</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllMeetingRooms, createRoom, updateRoom, deleteRoom } from '../../api/meetingRoomApi'
import { getSessionStorage } from '../../utils/common'

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const adminId = ref(getSessionStorage("adminId"))

const form = ref({
    name: "",
    type: "classroom",
    maxCapacity: 1,
    availableStartTime: "",
    availableEndTime: "",
    equipmentIds: [],
    hourlyRentalPrice: 0,
    status: 'idle',
    roomId: 0,
    createBy: "",
    updateBy: "",
    createTime: "",
    updateTime: "new Date().toISOString()"
})

const rules = {
  name: [
    { required: true, message: '请输入会议室名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择会议室类型', trigger: 'change' }
  ],
  maxCapacity: [
    { required: true, message: '请输入座位数', trigger: 'blur' }
  ],
  hourlyRentalPrice: [
    { required: true, message: '请输入每小时价格', trigger: 'blur' }
  ],
  availableStartTime: [
    { required: true, message: '请选择可用开始时间', trigger: 'change' }
  ],
  availableEndTime: [
    { required: true, message: '请选择可用结束时间', trigger: 'change' }
  ]
}

// 模拟会议室数据
const roomList = ref([])

const resetForm = () => {
  form.value = {
    name: "",
    type: "classroom",
    maxCapacity: 1,
    availableStartTime: "",
    availableEndTime: "",
    equipmentIds: [],
    hourlyRentalPrice: 0,
    status: "idle",
    roomId: 0,
    createBy: "",
    updateBy:"",
    createTime: "",
    updateTime: ""
  }
}

const getMeetingRoomList = async () => {
  try{
    const response = await getAllMeetingRooms()
    console.log(response);
    if(response.flag){
      roomList.value = response.result
      console.log(roomList.value);
      
    }else{
      ElMessage.error(response.reason || '获取会议室列表失败')
    }
  }catch(error){
    console.error('获取会议室列表失败:', error)
  }

}


onMounted(() => {
  getMeetingRoomList()

})

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  form.value = {
    roomId: row.roomId,
    name: row.name,
    type: row.type,
    maxCapacity: row.maxCapacity,
    availableStartTime: "",
    availableEndTime: "",
    equipmentIds: Array.isArray(row.roomEquipments)
        ? row.roomEquipments.map(eq => String(eq.equipmentId))
        : [],
    hourlyRentalPrice: row.hourlyRentalPrice,
    status: row.status,
    createBy: "",
    updateBy: "",
    createTime: "",
    updateTime: ""
  }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  ElMessageBox.confirm(
    `确认删除会议室"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const response = await deleteRoom(row.roomId)
    if(response.flag){
      ElMessage.success('删除成功')
      getMeetingRoomList()
    }else{
      ElMessage.error(response.reason || '删除失败')
    }
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const currentTime = new Date().toISOString()
        console.log(form.value);
        let response
        if (isEdit.value) {
          response = await updateRoom(form.value.roomId,form.value)
        } else {
          response = await createRoom(form.value)
        }

        if (response.flag) {
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          getMeetingRoomList()
        } else {
          ElMessage.error(response.reason || (isEdit.value ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('保存会议室失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}
</script>

<style scoped>
.room-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ml-1 {
  margin-left: 4px;
}

.ml-2 {
  margin-left: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 